package com.thon.controller.rest;

import com.thon.commons.persistence.Page;
import com.thon.controller.util.BaseController;
import com.thon.entity.system.Question;
import com.thon.service.system.QuestionService;
import com.thon.service.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.validation.Valid;
import java.util.Date;

/**
 * Created by win on 2016/1/28.
 */
@Controller
@RequestMapping(value = "/api/question")
public class QuestionRestController extends BaseController {

    @Autowired
    private QuestionService questionService;

    //saveQuestion
    @RequestMapping(value="/save", method = RequestMethod.POST)
    public ResponseEntity<?> apiQuestionSave(@Valid Question question) {
        if(question.getUser() != null && question.getUser().getId() == null){
            question.setUser(null);
        }
        if(question.getAnswerContent() == null){
            question.setAnswerFinish(1);
        }
        if(question.getAnswerContent() != null){
            question.setAnswerFinish(0);
            question.setAnswerDate(new Date());
        }
        questionService.saveQuestion(question);
        return new ResponseEntity(true, HttpStatus.OK);
    }

    //deleteQuestion
    @RequestMapping(value="/del", method = RequestMethod.POST)
    public ResponseEntity<?> apiQuestionDel(@RequestParam("id") int id) {
        if(UserUtils.getUser().isAdmin()){
            Question question = questionService.getQuestion(id);
            questionService.deleteQuestion(question);
            return new ResponseEntity("true", HttpStatus.OK);
        }else {
            return new ResponseEntity("false", HttpStatus.FORBIDDEN);
        }
    }

    //listQuestions
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ResponseEntity<?> list(@RequestParam(value = "p", defaultValue = "1") int pageNo,
                                  @RequestParam(value = "s", defaultValue = PAGE_SIZE) int pageSize,
                                  @RequestParam(value = "orderName", defaultValue = "id") String orderName,
                                  @RequestParam(value = "order", defaultValue = "desc") String order,
                                  Question question) {

        Page<Question> page = new Page<Question>();
        page.setPageNo(pageNo);
        page.setPageSize(pageSize);
        page = questionService.findQuestions(page,question, orderName, order);
        return new ResponseEntity(page, HttpStatus.OK);
    }
}
